package com.wnxy.sddfp.bank.mq;

import com.wnxy.sddfp.common.constant.MQConstant;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {
    /**
     * 消息转换器
     */
    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 队列：sddfp-queue-card
     * 交换机：sddfp-exchange-card
     * 路由key：card.#
     * 创建队列
     */
    @Bean
    public Queue queueCard(){
        return QueueBuilder.durable(MQConstant.SDDFP_CARD_QUEUE).build();
    }


    /**
     * 创建交换机
     */
    @Bean
    public Exchange exchangeCard(){
        return ExchangeBuilder.topicExchange(MQConstant.SDDFP_CARD_EXCHANGE).build();
    }

    /**
     * 队列绑定到交换机
     */
    @Bean
    public Binding cardBinding(Queue queueCard,Exchange exchangeCard){
        return BindingBuilder
                .bind(queueCard).to(exchangeCard).with(MQConstant.SDDFP_CARD_ROUTING).noargs();
    }

    /**
     * 配置RabbitAdmin，解决项目启动时候没有自动创建队列、交换机的问题
     */
    @Bean
    public RabbitAdmin rabbitAdmin(
            ConnectionFactory connectionFactory,Queue queueCard,Exchange exchangeCard){
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        rabbitAdmin.declareQueue(queueCard);
        rabbitAdmin.declareExchange(exchangeCard);
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }
}
